<script setup lang="tsx">
import { computed, PropType, reactive, ref } from 'vue'
import { Dialog } from '@/components/Dialog'
import { ElForm, ElMessage, FormInstance, FormRules } from 'element-plus'
import { useDesign } from '@/hooks/web/useDesign'
import { Plus } from '@element-plus/icons-vue'
import { SelectOption } from '@/api/common/types'
import { getDictionarySelectOptionList } from '@/utils/dictionary'
import { SystemUser } from '@/api/system/user/types'
import {
  checkEmailApi,
  checkMobileApi,
  checkUserNameApi,
  createSystemUserApi,
  updateSystemUserApi
} from '@/api/system/user'

const props = defineProps({
  modelValue: {
    type: Boolean
  },
  refreshList: {
    type: Function,
    required: true
  },
  user: {
    type: Object as PropType<SystemUser>
  },
  title: {
    type: String
  },
  create: {
    type: Boolean
  }
})
const validateUserName = (rule, value, callback) => {
  if (value === undefined || value === null || value === '') {
    callback(new Error('用户名不能为空'))
  } else {
    checkUserNameApi({
      userName: value,
      userId: systemUser.userId
    })
      .then((res) => {
        if (res?.data) {
          callback(new Error(res?.data))
        } else {
          callback()
        }
      })
      .catch(() => {
        callback(new Error('请求异常，请联系管理员！'))
      })
  }
}
const validateLoginPwd = (rule, value, callback) => {
  if (value === undefined || value === null || value === '') {
    callback(new Error('登录密码不能为空'))
  } else {
    if (value.length > 16 || value.length < 8) {
      callback(new Error('密码必须是8到16位'))
    }
    let reg = /^[A-Za-z0-9]+$/
    if (!reg.test(value)) {
      callback(new Error('密码必须是数字或英文字母的组合'))
    }
    callback()
  }
}
const validateMobile = (rule, value, callback) => {
  if (value === undefined || value === null || value === '') {
    callback(new Error('手机号不能为空'))
  } else {
    checkMobileApi({
      mobile: value,
      userId: systemUser.userId
    })
      .then((res) => {
        if (res?.data) {
          callback(new Error(res?.data))
        } else {
          callback()
        }
      })
      .catch(() => {
        callback(new Error('请求异常，请联系管理员！'))
      })
  }
}
const validateEmail = (rule, value, callback) => {
  checkEmailApi({
    email: value,
    userId: systemUser.userId
  })
    .then((res) => {
      if (res?.data) {
        callback(new Error(res?.data))
      } else {
        callback()
      }
    })
    .catch((error) => {
      callback(new Error('请求异常，请联系管理员！'))
    })
}
const validateConfirmLoginPwd = (rule, value, callback) => {
  if (value === undefined || value === null || value === '') {
    callback(new Error('确认密码不能为空'))
  } else {
    if (value !== systemUser.loginPwd) {
      callback(new Error('两次密码不一致'))
    } else {
      callback()
    }
  }
}
const rules = reactive<FormRules<SystemUser>>({
  userName: [{ required: true, trigger: 'blur', validator: validateUserName }],
  loginPwd: [{ required: true, trigger: 'blur', validator: validateLoginPwd }],
  mobile: [{ required: true, trigger: 'blur', validator: validateMobile }],
  email: [{ required: false, trigger: 'blur', validator: validateEmail }],
  realName: [{ required: true, message: '真实姓名不能为空', trigger: 'blur' }],
  confirmLoginPwd: [{ required: true, trigger: 'blur', validator: validateConfirmLoginPwd }]
})
const systemUser = reactive<SystemUser>({
  userId: props.user?.userId,
  userName: props.user?.userName,
  loginPwd: props.user?.loginPwd,
  orgId: props.user?.orgId,
  dataPermissionRange: props.user?.dataPermissionRange,
  mobile: props.user?.mobile,
  userStatus: props.user?.userStatus,
  email: props.user?.email,
  realName: props.user?.realName,
  headSculpture: props.user?.headSculpture,
  gender: props.user?.gender,
  birthday: props.user?.birthday,
  lastLoginTime: props.user?.lastLoginTime,
  introduction: props.user?.introduction,
  loginAddress: props.user?.loginAddress,
  createUserId: props.user?.createUserId,
  createTime: props.user?.createTime,
  operateId: props.user?.operateId,
  operateTime: props.user?.operateTime
})
const loading = ref(false)
const emit = defineEmits(['update:modelValue'])
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit('update:modelValue', val)
  }
})
const userFormRef = ref<FormInstance>()
const createUser = async () => {
  loading.value = true
  await userFormRef.value?.validate(async (isValid) => {
    console.log(isValid)
    if (isValid) {
      console.log('createSystemUser====', systemUser)
      const res = await createSystemUserApi(systemUser)
      console.log('createUserRes====', res)
      ElMessage.success('新增成功')
      if (props.refreshList) {
        props.refreshList()
      }
      dialogVisible.value = false
    }
    loading.value = false
  })
}
const updateUser = async () => {
  loading.value = true
  await userFormRef.value?.validate(async (isValid) => {
    console.log(isValid)
    if (isValid) {
      console.log('updateSystemUser====', systemUser)
      const res = await updateSystemUserApi(systemUser)
      console.log('updateUserRes====', res)
      ElMessage.success('编辑成功')
      if (props.refreshList) {
        props.refreshList()
      }
      dialogVisible.value = false
    }
    loading.value = false
  })
}
const uploadUrl = ref('http://localhost:8081/firefly/common/upload')
const handleAvatarSuccess = (res) => {
  systemUser.headSculpture = res.data
}
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}
const orgList = ref<SelectOption[]>()
const dataPermissionRangeList = ref<SelectOption[]>()
const userStatusList = ref<SelectOption[]>()
const genderList = ref<SelectOption[]>()
const getDictionaryList = async () => {
  dataPermissionRangeList.value = getDictionarySelectOptionList('dataPermissionRange')
  userStatusList.value = getDictionarySelectOptionList('status')
  genderList.value = getDictionarySelectOptionList('gender')
}
getDictionaryList()
const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('form')
</script>
<template>
  <div>
    <Dialog v-model="dialogVisible" :title="props.title">
      <el-form
        ref="userFormRef"
        :model="systemUser"
        :rules="rules"
        label-width="100px"
        label-position="right"
        status-icon
        :class="prefixCls"
        style="padding-right: 50px; padding-top: 10px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="systemUser.userName" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="systemUser.mobile" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="props.create">
          <el-col :span="12">
            <el-form-item label="密码" prop="loginPwd">
              <el-input
                v-model="systemUser.loginPwd"
                placeholder="请输入8-16位由数字、英文字母组合"
                show-password
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmLoginPwd">
              <el-input
                v-model="systemUser.confirmLoginPwd"
                placeholder="请输入确认密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="头像" prop="headSculpture">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="systemUser.headSculpture"
                  :src="systemUser.headSculpture"
                  class="avatar"
                  alt="头像"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织机构" prop="orgId">
              <el-select v-model="systemUser.orgId" placeholder="请选择组织机构">
                <el-option
                  v-for="item in orgList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="systemUser.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="systemUser.email" placeholder="请输入电子邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="systemUser.gender" size="large">
                <el-radio-button v-for="item in genderList" :key="item.value" :label="item.value">{{
                  item.label
                }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                value-format="YYYY-MM-DD"
                v-model="systemUser.birthday"
                :editable="false"
                placeholder="选择日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数据权限" prop="dataPermissionRange">
              <el-select v-model="systemUser.dataPermissionRange" placeholder="请选择数据权限">
                <el-option
                  v-for="item in dataPermissionRangeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="userStatus">
              <el-select v-model="systemUser.userStatus" placeholder="请选择用户状态">
                <el-option
                  v-for="item in userStatusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="个人介绍" prop="introduction">
              <el-input
                v-model="systemUser.introduction"
                :autosize="{ minRows: 4, maxRows: 8 }"
                type="textarea"
                placeholder="请输入个人介绍"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button
          type="primary"
          :loading="loading"
          @click="props.create ? createUser() : updateUser()"
          >保存</el-button
        >
        <el-button @click="dialogVisible = false">取消</el-button>
      </template>
    </Dialog>
  </div>
</template>
<style lang="less" scoped>
.avatar-uploader {
  height: 90px;
  width: 90px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 90px;
  height: 90px;
  line-height: 90px;
  text-align: center;
  border: 1px solid rgb(220, 223, 230);
  border-radius: 5px;
}

.avatar {
  width: 90px;
  height: 90px;
  display: block;
}
</style>
